package com.zzf.sus_time

import android.R
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.graphics.Color
import android.graphics.PixelFormat
import android.graphics.drawable.GradientDrawable
import android.os.*
import android.util.Log
import android.util.TypedValue
import android.view.*
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.NotificationCompat
import java.text.SimpleDateFormat
import java.util.*

class ClockService : Service() {
    private lateinit var windowManager: WindowManager
    private lateinit var clockView: TextView
    private lateinit var container: FrameLayout  // 类型更明确
    private lateinit var closeButton: ImageView
    private lateinit var closeArea: LinearLayout


    private val handler = Handler(Looper.getMainLooper())

    private val updateTime = object : Runnable {
        override fun run() {
            val now = System.currentTimeMillis()
            val time = SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date(now))
            clockView.text = time

            // 计算距离下一个整秒还有多久
            val delay = 1000 - (now % 1000)
            handler.postDelayed(this, delay)
        }
    }




    private fun createNotification(): Notification {
        val channelId = "clock_channel"
        return NotificationCompat.Builder(this, channelId)
            .setContentTitle("悬浮时钟运行中")
            .setSmallIcon(android.R.drawable.ic_lock_idle_alarm)
            .build()
    }

    private fun createNotificationChannel() {
        val serviceChannel = NotificationChannel(
            "clock_channel",
            "Clock Service Channel",
            NotificationManager.IMPORTANCE_LOW
        )
        val manager = getSystemService(NotificationManager::class.java)
        manager.createNotificationChannel(serviceChannel)
    }

    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
        startForeground(1, createNotification())


    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d("ClockService", "onStartCommand called")
        val textColor = intent?.getStringExtra("textColor") ?: "#FF0000"

        try {
            createNotificationChannel()
            startForeground(1, createNotification())
            container = FrameLayout(this)


            val textSize = intent?.getFloatExtra("textSize", 20f) ?: 20f
            windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
            clockView = TextView(this).apply {
                this.textSize = textSize
                setTextColor(Color.parseColor(textColor)) // 文本颜色
                setBackgroundColor(Color.parseColor("#80000000")) // 半透明黑色背景
                setPadding(20, 10, 20, 10) // 内边距
                // 设置圆角背景
                val shapeDrawable = GradientDrawable()
                shapeDrawable.cornerRadius = 20f
                shapeDrawable.setColor(Color.parseColor("#80000000")) // 背景色
                background = shapeDrawable
                // 设置阴影
                setLayerType(View.LAYER_TYPE_SOFTWARE, null) // 启用硬件加速
                setShadowLayer(4f, 2f, 2f, Color.BLACK)
                // 确保clockView可点击
                isClickable = true
                isLongClickable = true // 允许长按
            }
            clockView.setTextIsSelectable(false)

            closeButton = ImageView(this).apply {
                setImageResource(android.R.drawable.ic_menu_close_clear_cancel)
                setBackgroundColor(Color.RED)
                visibility = View.GONE
                setOnClickListener {
                    // 用户点击关闭按钮，移除悬浮窗
                    windowManager.removeView(container)
                    stopSelf()  // 如果需要关闭服务
                }
            }

            // 为关闭按钮设置固定位置（右上角）
            val closeParams = WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                        WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
                        WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                PixelFormat.TRANSLUCENT
            )
            closeParams.gravity = Gravity.TOP or Gravity.END // 右上角
            closeParams.x = 0
            closeParams.y = 0


             closeArea = LinearLayout(this).apply {
                orientation = LinearLayout.VERTICAL
                gravity = Gravity.CENTER
                visibility = View.GONE
                setPadding(40, 40, 40, 40) // 增加触发区域
                setBackgroundColor(Color.parseColor("#66000000")) // 半透明背景

                // 提示文字
                val tipText = TextView(this@ClockService).apply {
                    text = "拖动到这里关闭"
                    setTextColor(Color.WHITE)
                    setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f)
                }

               // addView(closeBtn)
                addView(tipText)
            }

            clockView.setOnLongClickListener {
                closeArea.visibility = View.VISIBLE
                true
            }
            windowManager.addView(closeArea, closeParams)

            //container.addView(closeButton, closeParams)

            val params = WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                        WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
                        WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                PixelFormat.TRANSLUCENT
            )

            params.gravity = Gravity.TOP or Gravity.START
            params.x = 100
            params.y = 100

            clockView.setOnTouchListener(FloatingTouchListener(params))
            container.addView(clockView)

            try {

                windowManager.addView(container, params)
            } catch (e: Exception) {
                Log.e("ClockService", "添加悬浮窗失败: ${e.message}")
            }
            handler.post(updateTime)

        } catch (e: Exception) {
            Log.e("ClockService", "Error: ${e.message}")
        }
        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        shutDownService();
    }

    fun shutDownService(){
        try {
            // 移除更新回调
            handler.removeCallbacks(updateTime)

            // 只在视图已经添加到 windowManager 时移除它
            if (::container.isInitialized && container.parent != null) {
                windowManager.removeView(container)
                Log.d("ClockService", "Clock view removed from window manager.")
            } else {
                Log.d("ClockService", "Clock view not attached to window manager.")
            }
        } catch (e: Exception) {
            Log.e("ClockService", "Error in onDestroy: ${e.message}")
        }
    }



    override fun onBind(intent: Intent?): IBinder? = null

    inner class FloatingTouchListener(private val params: WindowManager.LayoutParams) : View.OnTouchListener {
        private var initialX = 0
        private var initialY = 0
        private var initialTouchX = 0f
        private var initialTouchY = 0f

        override fun onTouch(v: View, event: MotionEvent): Boolean {
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    initialX = params.x
                    initialY = params.y
                    initialTouchX = event.rawX
                    initialTouchY = event.rawY

                    // 允许长按事件触发
                    v.performClick()
                    return false // 返回false让长按监听器也能收到事件
                }

                MotionEvent.ACTION_MOVE -> {
                    params.x = initialX + (event.rawX - initialTouchX).toInt()
                    params.y = initialY + (event.rawY - initialTouchY).toInt()
                    windowManager.updateViewLayout(container, params)

                    return true
                }
                MotionEvent.ACTION_UP->{
                    val location = IntArray(2)
                    closeArea.getLocationOnScreen(location)
                    val closeX = location[0]
                    val closeY = location[1]
                    val closeW = closeArea.width
                    val closeH = closeArea.height
                    val touchX = event.rawX.toInt()
                    val touchY = event.rawY.toInt()
                    if (touchX in closeX..(closeX + closeW) && touchY in closeY..(closeY + closeH)) {
                        // 高亮提示
                        closeArea.setBackgroundColor(Color.parseColor("#AAFF4444"))
                        (closeArea.getChildAt(1) as? TextView)?.setTextColor(Color.YELLOW)
                        shutDownService()
                    } else {
                        closeArea.setBackgroundColor(Color.parseColor("#66000000"))
                        (closeArea.getChildAt(1) as? TextView)?.setTextColor(Color.WHITE)
                    }


                    // 触摸抬起时，隐藏关闭按钮
                    closeArea.visibility = View.GONE
                    // 允许长按事件触发
                    v.performClick()
                    return false // 返回false让长按监听器也能收到事件
                }
            }
            return false
        }
    }
}
